package com.stone.framework.auth.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.stone.framework.auth.client.UserClient;
import com.stone.framework.core.exception.BusinessException;
import com.stone.framework.message.user.LoginInfoResBody;

public class GenericAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private UserClient userClient;

    /**
     * 权限验证在gateway实现，此处没有调用场景
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
        // SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // UserInfo userInfo = UserContext.getUser();
        // info.setRoles(new HashSet<>(userInfo.getRoles()));
        // info.setStringPermissions(new HashSet<>(userInfo.getPermissions()));
        // return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token.getPrincipal() == null) {
            return null;
        }
        String username = token.getPrincipal().toString();
        LoginInfoResBody user = userClient.getLoginInfo(username);
        if (user == null) {
            throw new BusinessException("获取用户登录信息失败");
        }
        return new SimpleAuthenticationInfo(user.getName(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()),
            getName());
    }

}
